package com.qiche.controller.mgr;

import com.qiche.aspect.Result;
import com.qiche.constant.AccountType;
import com.qiche.dto.StatisticsDto;
import com.qiche.enums.ResultEnum;
import com.qiche.model.*;
import com.qiche.service.*;
import com.qiche.util.DateTimeUtils;
import com.qiche.util.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 统计管理控制器
 * @author Linzewen
 *
 *         2018年2月27日
 */
@RestController
@RequestMapping("/statistics")
public class StatisticsController {

	@Resource
	private InsurancePolicyService policyService;

	@Resource
	private CardService cardService;

	@Resource
	private SubscribeService subscribeService;

	@Resource
	private  StoreMemberService storeMemberService;

	@Resource
	private MerchantService merchantService;

	@Autowired
	private UserRoleService userRoleService;

	@Autowired
	private RoleService roleService;

	@GetMapping(value = "/get")
	public Result<StatisticsDto> get() {

		SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM");
		User currentUser=UserUtils.getCurrentUser();

		StatisticsDto dto = new StatisticsDto();

		UserRole userRole=userRoleService.selectByUserId(currentUser.getId());
		if(userRole!= null){
			Role role =roleService.selectByKey(userRole.getRoleid());
			dto.setLoginUser(currentUser.getUsername()+"["+role.getRoleName()+"]");
		}


		/*}else{
			Merchant merchant=merchantService.selectById(currentUser.getMerchantId().longValue());
			dto.setLoginUser(currentUser.getUsername()+"("+merchant.getName()+")");
		}*/
		Map<String, Integer> memberStat = new HashMap<>();
		Map<String, Integer> policyStat = new HashMap<>();

		Map<String, Integer> cardVerifyStat = new HashMap<>();
		Map<String, Integer> cardMoneyStat = new HashMap<>();
		Map<String, Integer> orderStat = new HashMap<>();
		Map<String, Integer> orderMoneyStat = new HashMap<>();
		List<Long> orderMoneyGroupByMonth =new ArrayList<>();
		List<Long> cardMoneyGroupByMonth =new ArrayList<>();

		for (int i=1;i<=12;i++){
			orderMoneyGroupByMonth.add(0L);
			cardMoneyGroupByMonth.add(0L);
		}

		List<StoreMember> storeMemberList = null;
		List<InsurancePolicy> policyList = null;
		List<Card> cardVerifyList = null;
		List<Subscribe> orderList = null;
		subscribeService.selectAllColseByMerchantId(UserUtils.getCurrentUser().getMerchantId());
		if (AccountType.ADMIN == UserUtils.getCurrentUser().getAccountType()) {
			storeMemberList=	storeMemberService.selectByExample(null);
			//memberList = memberService.selectByExample(null);
			policyList = policyService.selectByExample(null);
			cardVerifyList = cardService.selectCardAmountAllByMerchantId(null);
			orderList = subscribeService.selectAllColseByMerchantId(null);
		} else {
			storeMemberList=storeMemberService.selectByMerchantId();
			//storeMemberList=storeMemberService.selectByMerchantId(currentUser.getMerchantId().longValue());
			//memberList = memberService.selectByMerchantId();
			policyList = policyService.selectByMerchantId();
			cardVerifyList = cardService.selectCardAmountAllByMerchantId(UserUtils.getCurrentUser().getMerchantId());
			orderList = subscribeService.selectAllColseByMerchantId(UserUtils.getCurrentUser().getMerchantId());
		}

		Integer todayMemberCount = (int) storeMemberList.stream()
				.filter(member -> DateTimeUtils.isToday(member.getCreateTime().getTime()) == true).count();
		Integer thisMonthMemberCount = (int) storeMemberList.stream()
				.filter(member -> DateTimeUtils.isThisMonth(member.getCreateTime().getTime()) == true).count();

		memberStat.put("total", storeMemberList.size());
		memberStat.put("today", todayMemberCount);
		memberStat.put("thisMonth", thisMonthMemberCount);
		dto.setMemberStat(memberStat);

		Integer todayPolicyCount = (int) policyList.stream()
				.filter(policy -> DateTimeUtils.isToday(policy.getCreateTime().getTime()) == true).count();
		Integer thisMonthPolicyCount = (int) policyList.stream()
				.filter(policy -> DateTimeUtils.isThisMonth(policy.getCreateTime().getTime()) == true).count();

		policyStat.put("total", policyList.size());
		policyStat.put("today", todayPolicyCount);
		policyStat.put("thisMonth", thisMonthPolicyCount);
		dto.setPolicyStat(policyStat);

		Integer todayCardVerifyCount = (int) cardVerifyList.stream()
				.filter(cardVerify -> DateTimeUtils.isToday(cardVerify.getWriteoffDate().getTime()) == true).count();
		Integer thisMonthCardVerifyCount = (int) cardVerifyList.stream()
				.filter(cardVerify -> DateTimeUtils.isThisMonth(cardVerify.getWriteoffDate().getTime()) == true)
				.count();

		cardVerifyStat.put("total", cardVerifyList.size());
		cardVerifyStat.put("today", todayCardVerifyCount);
		cardVerifyStat.put("thisMonth", thisMonthCardVerifyCount);
		dto.setCardVerifyStat(cardVerifyStat);

		Integer cardTotalMoney = cardVerifyList.stream().mapToInt(card -> card.getCardAmount().intValue()).sum();
		Integer todayCardTotalMoney = cardVerifyList.stream()
				.filter(cardVerify -> DateTimeUtils.isToday(cardVerify.getWriteoffDate().getTime()) == true)
				.mapToInt(card -> card.getCardAmount().intValue()).sum();
		Integer thisMonthCardTotalMoney = cardVerifyList.stream()
				.filter(cardVerify -> DateTimeUtils.isThisMonth(cardVerify.getWriteoffDate().getTime()) == true)
				.mapToInt(card -> card.getCardAmount().intValue()).sum();

		Map<String, List<Card>> cvfMaps = cardVerifyList.stream().collect(Collectors.groupingBy(s -> formatter.format(s.getWriteoffDate())));

		cvfMaps.forEach((k, v) ->
				cardMoneyGroupByMonth.set(Integer.parseInt(k.split("-")[1])-1,Long.parseLong(v.stream().mapToInt(order -> order.getCardAmount().intValue()).sum()+""))

		);

		cardMoneyStat.put("total", cardTotalMoney);
		cardMoneyStat.put("today", todayCardTotalMoney);
		cardMoneyStat.put("thisMonth", thisMonthCardTotalMoney);




		Integer todayOrderCount = (int) orderList.stream()
				.filter(order -> DateTimeUtils.isToday(order.getBalanceTime().getTime()) == true).count();
		Integer thisMonthOrderCount = (int) orderList.stream()
				.filter(order -> DateTimeUtils.isThisMonth(order.getBalanceTime().getTime()) == true).count();

		orderStat.put("total", orderList.size());
		orderStat.put("today", todayOrderCount);
		orderStat.put("thisMonth", thisMonthOrderCount);
		dto.setCardVerifyStat(orderStat);

		Integer orderTotalMoney = orderList.stream().mapToInt(order -> order.getProducesMoney().intValue()).sum();
		Integer todayOrderTotalMoney = orderList.stream()
				.filter(order -> DateTimeUtils.isToday(order.getBalanceTime().getTime()) == true)
				.mapToInt(order -> order.getProducesMoney().intValue()).sum();
		Integer thisMonthOrderTotalMoney = orderList.stream()
				.filter(order -> DateTimeUtils.isThisMonth(order.getBalanceTime().getTime()) == true)
				.mapToInt(card -> card.getProducesMoney().intValue()).sum();


		Map<String, List<Subscribe>> omgMaps = orderList.stream().collect(Collectors.groupingBy(s -> formatter.format(s.getBalanceTime())));

		omgMaps.forEach((k, v) ->
				orderMoneyGroupByMonth.set(Integer.parseInt(k.split("-")[1])-1,Long.parseLong(v.stream().mapToInt(order -> order.getProducesMoney().intValue()).sum()+""))

				);

		orderMoneyStat.put("total", orderTotalMoney);
		orderMoneyStat.put("today", todayOrderTotalMoney);
		orderMoneyStat.put("thisMonth", thisMonthOrderTotalMoney);

		dto.setMemberStat(memberStat);
		dto.setCardMoneyStat(cardMoneyStat);
		dto.setCardVerifyStat(cardVerifyStat);
		dto.setOrderMoneyStat(orderMoneyStat);
		dto.setOrderStat(orderStat);
		dto.setPolicyStat(policyStat);
		dto.setMonthsInCurrentYear(getMonthsInCurrentYear());
		dto.setCardMoneyGroupByMonth(cardMoneyGroupByMonth);
		dto.setOrderMoneyGroupByMonth(orderMoneyGroupByMonth);


		return Result.createByResultEnum(ResultEnum.SUCCESS, dto);

	}


	public static List<String> getMonthsInCurrentYear(){
		Calendar calendar=Calendar.getInstance();
		int currentYear=calendar.get(Calendar.YEAR);
		String year=currentYear+"";
		List<String> list=new ArrayList<>();
		for (int i=1;i<=12;i++){
			list.add(year+"-"+i);
		}
		return list;
	}
}
